#!/usr/bin/env python3
"""
虚拟环境设置脚本
用于自动创建和配置Python虚拟环境
"""
import subprocess
import sys
import os
from pathlib import Path


def run_command(command, check=True):
    """执行命令并处理错误"""
    print(f"执行命令: {command}")
    try:
        result = subprocess.run(
            command, 
            shell=True, 
            check=check, 
            capture_output=True, 
            text=True
        )
        if result.stdout:
            print(result.stdout)
        return result
    except subprocess.CalledProcessError as e:
        print(f"命令执行失败: {e}")
        if e.stderr:
            print(f"错误信息: {e.stderr}")
        if check:
            sys.exit(1)
        return e


def setup_virtual_environment():
    """设置虚拟环境"""
    print("=== 校园视频孪生系统 - 虚拟环境设置 ===")
    
    # 检查Python版本
    python_version = sys.version_info
    if python_version.major < 3 or python_version.minor < 8:
        print("错误: 需要Python 3.8或更高版本")
        sys.exit(1)
    
    print(f"Python版本: {python_version.major}.{python_version.minor}.{python_version.micro}")
    
    # 虚拟环境目录
    venv_dir = Path("venv")
    
    # 创建虚拟环境
    if not venv_dir.exists():
        print("创建虚拟环境...")
        run_command(f"{sys.executable} -m venv venv")
    else:
        print("虚拟环境已存在")
    
    # 确定激活脚本路径
    if os.name == 'nt':  # Windows
        activate_script = venv_dir / "Scripts" / "activate"
        python_executable = venv_dir / "Scripts" / "python.exe"
        pip_executable = venv_dir / "Scripts" / "pip.exe"
    else:  # Linux/Mac
        activate_script = venv_dir / "bin" / "activate"
        python_executable = venv_dir / "bin" / "python"
        pip_executable = venv_dir / "bin" / "pip"
    
    # 升级pip
    print("升级pip...")
    run_command(f"{python_executable} -m pip install --upgrade pip")
    
    # 安装基础依赖
    print("安装基础依赖...")
    if Path("requirements.txt").exists():
        run_command(f"{pip_executable} install -r requirements.txt")
    else:
        print("警告: requirements.txt 文件不存在")
    
    # 询问是否安装AI依赖
    install_ai = input("是否安装AI相关依赖? (y/N): ").lower().strip()
    if install_ai in ['y', 'yes']:
        print("安装AI依赖...")
        if Path("requirements-ai.txt").exists():
            run_command(f"{pip_executable} install -r requirements-ai.txt")
        else:
            print("警告: requirements-ai.txt 文件不存在")
    
    # 创建.env文件
    env_file = Path(".env")
    if not env_file.exists():
        print("创建.env配置文件...")
        if Path(".env.example").exists():
            import shutil
            shutil.copy(".env.example", ".env")
            print("请编辑.env文件配置相关参数")
        else:
            print("警告: .env.example 文件不存在")
    
    print("\n=== 虚拟环境设置完成 ===")
    print(f"激活虚拟环境: source {activate_script}" if os.name != 'nt' else f"激活虚拟环境: {activate_script}")
    print("启动应用: python main.py")
    print("或使用: uvicorn main:app --reload")


if __name__ == "__main__":
    setup_virtual_environment()